package com.example.datahub;

import java.io.*;
import java.nio.charset.Charset;

public class CommandTest {
    private static String osCharset = (String) System.getProperties().get("sun.jnu.encoding");
    public static void main(String[] args) {
        try {
            System.out.println(System.getProperties().get("sun.jnu.encoding"));
            System.out.println(System.getProperties().get("file.encoding"));
            System.out.println(Charset.defaultCharset().displayName());
            System.out.println(System.getProperty("java.home"));

            // 构建命令
            ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", "tree","d:/a","&&","tree1","D:\\nacos-2.1.0");
            // 异常流输出到 getInputStream()
            //processBuilder.redirectErrorStream(true);

            // 执行命令
            Process process = processBuilder.start();
            // jdk 9 开始
            //process.pid();
            // 获取命令输出结果
            printStream("标准输出",process.getInputStream());
            printStream("异常输出",process.getErrorStream());
            OutputStream outputStream = process.getOutputStream();
            outputStream.write("ctrl+c".getBytes());

            // 等待命令执行完成
            int exitCode = process.waitFor();

            System.out.println("Exit Code: " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void printStream(String tag, InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,osCharset));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(tag+"："+line);
        }
    }
}
